package com.yoso.thread;

import cn.hutool.core.thread.ThreadUtil;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

public class CreatThread {

    static class YosoThread extends Thread {
        @Override
        public void run() {
            ThreadUtil.sleep(300);
            System.out.println("YosoThread.run");
        }
    }

    @Test
    public void thread(){
        YosoThread yosoThread = new YosoThread();
        yosoThread.start();
        System.out.println("done");
    }


    static class YosoRunnable implements Runnable {
        @Override
        public void run() {
            ThreadUtil.sleep(300);
            System.out.println("CreatThread.runnable");
        }
    }
    @Test
    public void runnable(){
        Thread thread = new Thread(new YosoRunnable());
        thread.start();
    }


    static class YosoCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            ThreadUtil.sleep(300);
            System.out.println("YosoCallable.call");
            return "call";
        }
    }



   @Test
   public void callable(){
       YosoCallable yosoCallable = new YosoCallable();
       FutureTask<String> target = new FutureTask<>(yosoCallable);
       Thread thread = new Thread(target);
       thread.start();
       thread.start();
       String s = null;
       try {
           s = target.get();
       } catch (InterruptedException e) {
           System.out.println("InterruptedException");
           throw new RuntimeException(e);
       } catch (ExecutionException e) {
           System.out.println("ExecutionException");
           throw new RuntimeException(e);
       }
       System.out.println("s = " + s);
   }

   @Test
   @SneakyThrows
   public void pool(){
       ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
               1, 1, 20, TimeUnit.SECONDS, new LinkedBlockingDeque<>(),
               new ThreadFactory() {
                   @Override
                   public Thread newThread(Runnable r) {
                       System.out.println("创建新线程");
                       return new Thread(r);
                   }
               }, new ThreadPoolExecutor.AbortPolicy());

       Future<?> runableFuture = threadPoolExecutor.submit(new YosoRunnable());
       Object o = runableFuture.get();
       System.out.println("o = " + o);
       Future<String> runableCallable = threadPoolExecutor.submit(new YosoCallable());
       Object o2 = runableCallable.get();
       System.out.println("o2 = " + o2);
       Future<?> runableThread = threadPoolExecutor.submit(new YosoThread());
       Object o3 = runableThread.get();
       System.out.println("o3 = " + o3);
       ThreadUtil.sleep(2000);

   }

}
